package com.qf.cloud2202.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

//@Component
public class TokenGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        System.out.println("=======================");
        System.out.println(exchange);

        // 获取请求对象
        final ServerHttpRequest request = exchange.getRequest();

        // 获取请求头对象
        final HttpHeaders headers = request.getHeaders();

        // 获取指定请求头的内容
        final List<String> list = headers.get("jwttoken");
        if (list!=null){
            final String jwtToken = list.get(0);  // 获取请求头中的jwttoken
            // 校验jwt是否合法
            if (jwtToken==null || !jwtToken.equals("123456")){

                exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
                // 当前请求就此停住，不再往后面的微服务进行转发了
                return exchange.getResponse().setComplete();
            }
        }else {
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            // 当前请求就此停住，不再往后面的微服务进行转发了
            return exchange.getResponse().setComplete();
        }


        return chain.filter(exchange); // 放行当前请求，让请求继续走后面的过滤器和后面的 微服务
    }

    /**
     * 该接口返回的数值代表了过滤器执行的顺序，数值越小，该过滤器越早被执行
     * @return
     */
    @Override
    public int getOrder() {
        return 10;
    }
}
